home *** CD-ROM | disk | FTP | other *** search
- Path: charnel.ecst.csuchico.edu!mcelroy
- From: mcelroy@ecst.csuchico.edu (James Robert McElroy)
- Newsgroups: comp.lang.c++
- Subject: Re: Virtual Members: Difficult Question
- Date: 19 Jan 1996 18:38:33 GMT
- Organization: California State University, Chico
- Message-ID: <4doof9$hom@charnel.ecst.csuchico.edu>
- References: <4dmha6$80c@marlin.ssnet.com>
- NNTP-Posting-Host: hairball.ecst.csuchico.edu
-
- A general comment about your code:
-
- You are casting the wrong way in the inheritance hierarchy.
- This is guaranteed to blow up at some point, often unpredic-
- tably. Some times it will work, some times it won't (similar
- to driving the wrong way down a one-way street).
-
- Look at it this way: in terms of physical space taken up by
- a class object, a base class object will always take up less room than
- a derived class object, right? Now, if you tell a base class object it is
- actually a derived class object (via the cast) the pointer now thinks
- it has more room in memory than it actually does.
-
- Let's say the base class object takes up 20
- bytes. Now, by definition, the derived class object must take up
- the same or more room, because it, in essence, contains the
- base class object. Let's say you have a derived class object that
- takes 28 bytes of memery. So you cast a base class object to the
- derived class object pointer, and if you start messing around with bytes
- 21-28 via the pointer, you are tampering with memory that isn't yours!
-
- Look at it this way -- would the following code cause problems?
-
- int foo;
- long * fubar = (long*)&foo;
- *fubar = 10; // gee, no problem here
- *fubar = 32468551; // uh oh. Seems to crash. Don't know why!
-
- Yup. Similar to what you are experiencing.
-
- --
- Jim McElroy
- Calif. State Univ., Chico
- mcelroy@ecst.csuchico.edu
-